/*
 * @Author: atony2099
 * @Date: 2019-02-14 12:19:17
 * @Last Modified by: atony2099
 * @Last Modified time: 2019-02-15 11:11:43
 */

'use strict';

const Controller = require('egg').Controller;
const _ = require('lodash');

const loginValidate = {
  loginname: 'string',
  password: 'string',
};

class UseController extends Controller {
  async login() {
    // 1. validate
    const {
      ctx,
      ctx: { request },
      service,
    } = this;
    ctx.validate(loginValidate, request.body);
    const { loginname, password } = request.body;

    // 2.check user
    const user = await service.user.findUserByLoginnameAndPass(
      loginname,
      ctx.helper.createMD5(password)
    );
    if (!user) {
      this.ctx.toError(401, 'username or password error');
      return;
    }
    this.ctx.toSuccess({
      token: user.token,
    });
  }
  async user() {
    const { _id } = this.ctx.$userInfo;
    const user = await this.service.user.getUserByQuery({ _id });

    const userInfo = _.pick(user, [
      'username',
      'goldCount',
      'continusDay',
      'lastSignDate',
    ]);

    this.ctx.toSuccess({ userInfo });
  }
  async resetUser() {
    const { _id } = this.ctx.$userInfo;
    const user = await this.ctx.service.user.resetUserInfo(_id);
    const userInfo = _.pick(user, [
      'username',
      'goldCount',
      'continusDay',
      'lastSignDate',
    ]);
    this.ctx.toSuccess({ userInfo });
  }
}

module.exports = UseController;
